Queues

Queues (like the stacks in another recipe) are easy to implement in JavaScript. You use an array, and two variables representing the start and end of the queue.

: queue
1st Entry Last Entry


Discussion

Queues provide a good example of an array application; like stacks, they're easy to implement using JavaScript arrays. The kind of queue implemented here is called a circular queue. We've left something for you to do as an exercise: the code as written doesn't protect the end of the queue from overwriting the start of the queue if 51 items are added. How would you rewrite add() to keep this from happening?
var qStart = 0;              // First item added to the queue
var qEnd = 0;				 // Last item added to the queue

// Show the queue
function showqueue()
{
    var answer	= ""
    if(qStart != qEnd) {
        var i = qEnd;
        var fKeepOn = true;

        answer = queue[i];
        while(fKeepOn) {
           i++;
           if(i == 50)
              i = 0;
           if(i == qStart)
               fKeepOn = false;
           else					
               answer = answer + ':' + queue[i];
        }
    }
    document.forms[0].queue.value = answer;
    document.forms[0].start.value = qStart;
    document.forms[0].end.value = qEnd;
    document.forms[0].input.focus();
    document.forms[0].input.select();
}
    
    // Remove value from queue
function remove()
{
    if(qStart == qEnd) {
        alert('The queue is empty');
        return;
    }
    document.forms[0].input.value = queue[qEnd];
    qEnd++;
    if(qEnd > 49)
        qEnd = 0;
    showqueue();
}
    
// Add value to queue; this will overwrite first value
// if too many added
function add()
{
    queue[qStart++] = document.forms[0].input.value;
    if(qStart > 49)
        qStart = 0;
    showqueue();
}
Copyright ©1998 by Charles River Media, All Rights Reserved